//
//  HCCRMOperatingViewController.m
//  HelloCall
//
//  Created by WangYongpeng on 13-9-21.
//  Copyright (c) 2013年 HC. All rights reserved.
//

#import "HCCRMOperatingViewController.h"
#import "HCComMenuCell.h"
#import "HCCRMDetailViewController.h"
#import "HCRemarkListViewController.h"
#import "HCRemarkInfoViewController.h"
#import "HCCallPhonePopupView.h"
#import "HCCallRecordsModel.h"
#import "HCPickerView.h"
#import "HCMenuview.h"
#import "HCMainViewController.h"
#import "HCNetworkManger.h"
#import "HCLoginInfoModel.h"

#define kCustomTypeSelectTransaction (1234)
#define kCustomTypeSelectPotential (1235)
#define kCustomTypeSelectFollow (1236)
#define kCustomTypeSelectGiveUp (1237)

extern HCMainViewController* g_mainViewController;

@interface HCCRMOperatingViewController ()<HCComMenuCellDelegate,HCRemarkListViewControllerDelegate,HCPickerViewDelegate,HCMenuviewDelegate,HCModelDataObserver>
{
    ECRMOperatingType   m_operatingType;
    ECustomType         m_customType;
}
@property (nonatomic, retain) UITextView* textView;
@property (nonatomic, retain) UIView*       customTypeSelectView;
@property (nonatomic, retain) HCMenuview*   menuView;
@property (nonatomic, retain)UIActivityIndicatorView* activityIndicatorView;

@end

@implementation HCCRMOperatingViewController

@synthesize textView = m_textView;
@synthesize customTypeSelectView = m_customTypeSelectView;
@synthesize menuView = m_menuView;
@synthesize activityIndicatorView = m_activityIndicatorView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UIBarButtonItem* menuItem = [[[UIBarButtonItem alloc] initWithTitle:@"菜单" style:UIBarButtonItemStylePlain target:self action:@selector(menuItemPress:)] autorelease];
    self.navigationItem.leftBarButtonItem = menuItem;
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height - 80)];
    self.textView.textColor = [UIColor blackColor];
    self.textView.hidden = YES;
    self.textView.editable = NO;
    [self.view addSubview:self.textView];
    
    CGRect tableViewFrame = self.tableView.frame;
    tableViewFrame.origin.y += 44;
    self.tableView.frame = tableViewFrame;
    //用户类型选择条
    UIFont* font = [UIFont systemFontOfSize:14];
    self.customTypeSelectView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 45)] autorelease];
    UIImage* bgImage = [UIImage imageNamed:@"CRMListChangeBg.png"];
    UIImageView* bgImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.customTypeSelectView.bounds.size.width, self.customTypeSelectView.bounds.size.height)] autorelease];
    bgImageView.image = [bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [self.customTypeSelectView addSubview:bgImageView];
    
    
    UIImage* buttonImage = [[UIImage imageNamed:@"CRMListChangeButton.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    UIImage* buttonPressImage = [[UIImage imageNamed:@"CRMListChangeButtonPress.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    
//    self.customTypeSelectView.backgroundColor = [UIColor yellowColor];
    CGRect rect = CGRectMake(8, 7.5, 70, 30);
    UIButton* selectButton = [[[UIButton alloc] initWithFrame:rect] autorelease];
//    selectButton.backgroundColor = [UIColor orangeColor];
    selectButton.tag = kCustomTypeSelectTransaction;
    selectButton.titleLabel.font = font;
    [selectButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [selectButton setBackgroundImage:buttonPressImage forState:UIControlStateHighlighted];
    [selectButton setTitle:@"成交" forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [selectButton addTarget:self action:@selector(customTypeSelectPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.customTypeSelectView addSubview:selectButton];
    
    rect = CGRectMake(86, 7.5, 70, 30);
    selectButton = [[[UIButton alloc] initWithFrame:rect] autorelease];
//    selectButton.backgroundColor = [UIColor orangeColor];
    selectButton.tag = kCustomTypeSelectPotential;
    selectButton.titleLabel.font = font;
    [selectButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [selectButton setBackgroundImage:buttonPressImage forState:UIControlStateHighlighted];
    [selectButton setTitle:@"潜在" forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [selectButton addTarget:self action:@selector(customTypeSelectPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.customTypeSelectView addSubview:selectButton];
    
    rect = CGRectMake(162, 7.5, 70, 30);
    selectButton = [[[UIButton alloc] initWithFrame:rect] autorelease];
//    selectButton.backgroundColor = [UIColor orangeColor];
    selectButton.tag = kCustomTypeSelectFollow;
    selectButton.titleLabel.font = font;
    [selectButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [selectButton setBackgroundImage:buttonPressImage forState:UIControlStateHighlighted];
    [selectButton setTitle:@"继续跟进" forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [selectButton addTarget:self action:@selector(customTypeSelectPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.customTypeSelectView addSubview:selectButton];
    
    rect = CGRectMake(240, 7.5, 70, 30);
    selectButton = [[[UIButton alloc] initWithFrame:rect] autorelease];
//    selectButton.backgroundColor = [UIColor orangeColor];
    selectButton.tag = kCustomTypeSelectGiveUp;
    selectButton.titleLabel.font = font;
    [selectButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [selectButton setBackgroundImage:buttonPressImage forState:UIControlStateHighlighted];
    [selectButton setTitle:@"放弃" forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [selectButton addTarget:self action:@selector(customTypeSelectPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.customTypeSelectView addSubview:selectButton];
    
    [self.view addSubview:self.customTypeSelectView];
    [self setSelectedButtonHighlighted:kCustomTypeSelectTransaction];
    m_customType = ECustomType_Transaction;
    m_operatingType = ECRMOperatingType_CustomerList;
    [self setCRMOperatingType:m_operatingType];
    
    NSMutableArray* menuArray = [NSMutableArray arrayWithCapacity:4];
    menuDataNode* node = [[[menuDataNode alloc] init] autorelease];
    node.title = @"客户清单";
    node.menuId = ECRMOperatingType_CustomerList;
    [menuArray addObject:node];

    node = [[[menuDataNode alloc] init] autorelease];
    node.title = @"客户统计";
    node.menuId = ECRMOperatingType_Statistics;
    [menuArray addObject:node];
    
    self.menuView = [[[HCMenuview alloc] initWithFrame:CGRectMake(0, 0, 200, [[UIScreen mainScreen] bounds].size.height)] autorelease];
    self.menuView.delegate = self;
    self.menuView.menuDateArray = menuArray;
    [g_mainViewController setMenuView:self.menuView];
    
    if ([self getDataArray].count > 0)
    {
        [[HCNetworkManger shareManger] queryCustListByOffset:0];
    }
    else
    {
        [[HCNetworkManger shareManger] queryCustListByOffset:0];
    }
    
    m_activityIndicatorView = [[UIActivityIndicatorView alloc]
                                                  initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    
    [[HCSuperCRMModel defaultModel] addObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[HCSuperCRMModel defaultModel] removeObserver:self];
    self.textView = nil;
    self.customTypeSelectView = nil;
    self.menuView = nil;
    self.activityIndicatorView = nil;

    [super dealloc];
}

- (void)setSelectedButtonHighlighted:(int)tag
{
    for (UIButton* view in self.customTypeSelectView.subviews)
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            if (view.tag == tag)
            {
                [view setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }
            else
            {
                [view setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
        }
    }
}

- (void)customTypeSelectPress:(UIButton*)button
{
    switch (button.tag)
    {
        case kCustomTypeSelectTransaction:
        {
            m_customType = ECustomType_Transaction;
            break;
        }
        case kCustomTypeSelectPotential:
        {
            m_customType = ECustomType_Potential;
            break;
        }
        case kCustomTypeSelectFollow:
        {
            m_customType = ECustomType_Follow;
            break;
        }
        case kCustomTypeSelectGiveUp:
        {
            m_customType = ECustomType_GiveUp;
            break;
        }
        default:
            break;
    }
    [self setSelectedButtonHighlighted:button.tag];
    m_menuIndex = -1;
    
    [self.tableView reloadData];
}

- (void)showAllCallInfo
{
    NSString* text = @"查看总详情内容：\n\n";
    
    text = [text stringByAppendingFormat:@"员工ID:%@\n", [HCLoginInfoModel defaultModel].userID];
    text = [text stringByAppendingFormat:@"工作手机:%@\n", [HCLoginInfoModel defaultModel].userPhoneNumber];
    text = [text stringByAppendingFormat:@"总用户数:%d（个）\n", [[HCSuperCRMModel defaultModel] allCRMCustomCount]];
    text = [text stringByAppendingFormat:@"成交用户数:%d个\n", [[HCSuperCRMModel defaultModel] getCustomArrayByType:ECustomType_Transaction].count];
    text = [text stringByAppendingFormat:@"潜在用户数:%d个\n", [[HCSuperCRMModel defaultModel] getCustomArrayByType:ECustomType_Potential].count];
    text = [text stringByAppendingFormat:@"继续跟进数:%d个\n", [[HCSuperCRMModel defaultModel] getCustomArrayByType:ECustomType_Follow].count];
    text = [text stringByAppendingFormat:@"放弃沟通数:%d个\n", [[HCSuperCRMModel defaultModel] getCustomArrayByType:ECustomType_GiveUp].count];
    text = [text stringByAppendingFormat:@"通话总次数:%d次\n", [[HCSuperCRMModel defaultModel] sumCallCount]];
    text = [text stringByAppendingFormat:@"通话总时长:%d分钟\n", [[HCSuperCRMModel defaultModel] sumCallTime]];
    
    self.textView.text = text;
}

- (void)setCRMOperatingType:(ECRMOperatingType)operatingType
{
    self.textView.hidden = YES;
    self.tableView.hidden = NO;
    
    switch (operatingType)
    {
        case ECRMOperatingType_Statistics:
        {
            [[HCNetworkManger shareManger] queryCustState];
            
            self.title = @"客户统计";
            self.textView.hidden = NO;
            self.tableView.hidden = YES;
            self.customTypeSelectView.hidden = YES;
            [self showAllCallInfo];
            break;
        }
        case ECRMOperatingType_CustomerList:
        {
            self.title = @"客户清单";
            self.customTypeSelectView.hidden = NO;
            break;
        }
        default:
        {
            self.title = @"客户统计";
            break;
        }
    }
}

- (void)menuItemPress:(UIBarButtonItem*)button
{
    g_mainViewController.menuView = self.menuView;
    [g_mainViewController showOrCloseMenu];
}

- (NSArray*)getDataArray
{
    return [[HCSuperCRMModel defaultModel] getCustomArrayByType:m_customType];
}

#pragma mark -- UITableViewDataSource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = nil;
    if (m_menuIndex > -1 && indexPath.row == m_menuIndex)
    {
        NSString* key = @"MenuCell";
        cell = [tableView dequeueReusableCellWithIdentifier:key];
        if (nil == cell)
        {
            HCComMenuCell* menuCell = [[[HCComMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:key] autorelease];
            menuCell.delegate = self;
            cell = menuCell;
        }
    }
    else
    {
        NSString* key = @"CallInfo";
        cell = [tableView dequeueReusableCellWithIdentifier:key];
        if (nil == cell)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:key] autorelease];
        }
        int index = indexPath.row;
        if (m_menuIndex > -1 && index > m_menuIndex)
        {
            index--;
        }
        HCCRMCustomInfo* customInfo = [[self getDataArray] objectAtIndex:index];
        cell.textLabel.text = customInfo.customPhoneNumber;
        cell.detailTextLabel.text = customInfo.contact;
    }
    return cell;
}

#pragma mark -- UITableViewDelegate
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    HCCRMCustomInfo* customInfo = [[self getDataArray] objectAtIndex:indexPath.row];
//    HCCallPhonePopupView* view = [[HCCallPhonePopupView alloc] initByPhoneNumber:customInfo.customPhoneNumber contact:customInfo.contact];
//    [self.view addSubview:view];
//    [view release];
//    
//    [[HCCallRecordsModel defaultModel] addCallRecord:customInfo.customPhoneNumber];
//}

#pragma mark -- HCComMenuCellDelegate
- (void)showDetail
{
    HCCRMCustomInfo* info = [[self getDataArray] objectAtIndex:m_menuIndex - 1];
    [[HCNetworkManger shareManger] queryCustDetailByCustomId:info.userID];
    
    m_activityIndicatorView = [[UIActivityIndicatorView alloc]
                               initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
}

- (void)showRemark
{
    if (m_menuIndex < 1)
    {
        return;
    }
    
    HCRemarkListViewController* viewController = [[HCRemarkListViewController alloc] init];
    viewController.delegate = self;
    [viewController setCustomInfo:[[self getDataArray] objectAtIndex:m_menuIndex - 1]];
    
    [self showNextWindow:viewController];
}

- (void)changeState
{
    int currentSel = 0;
    
    CGRect wBounds = [UIScreen mainScreen].bounds;
    HCPickerView *pickerView =  [[ [ HCPickerView alloc ] initWithFrame: wBounds] autorelease];  ///<修改：增加autorelease。（系统设置组合框选择）liuqina, 2013/01/08
    pickerView.delegate = self;
    [pickerView addSuperView:self.view data:[NSArray arrayWithObjects:@"录入CRM",@"放弃跟踪",@"申请转移", nil] currentSel:currentSel settingItemName:nil];
}

- (void)callPhone
{
    if (m_menuIndex < 1)
    {
        return;
    }
    
    HCCRMCustomInfo* customInfo = [[self getDataArray] objectAtIndex:m_menuIndex - 1];
    HCCallPhonePopupView* view = [[HCCallPhonePopupView alloc] initByPhoneNumber:customInfo.customPhoneNumber contact:customInfo.contact];
    [self.view addSubview:view];
    [view release];
    
    [[HCCallRecordsModel defaultModel] addCallRecord:customInfo.customPhoneNumber];
}

#pragma mark -- HCRemarkListViewControllerDelegate
- (void)showRemarkInfoDetail:(HCCallRemarkInfo *)remarkInfo
{
    HCRemarkInfoViewController* viewController = [[HCRemarkInfoViewController alloc] init];
    viewController.remarkInfo = remarkInfo;
    
    [self showNextWindow:viewController];
}

#pragma mark -- HCPickerViewDelegate
- (void)userSelectedIndex:(int)index settingItemName:(NSString*)itemName
{
    HCCRMCustomInfo* customInfo = [[self getDataArray] objectAtIndex:m_menuIndex - 1];
    [[HCCallListModel defaultModel] addCallInfoByCustomInfo:customInfo callInfoType:(CallInfoType)(index + 1)];
    [[HCSuperCRMModel defaultModel] removeCustomInfoByUserId:customInfo.userID];
    [self.tableView reloadData];
}

#pragma mark -- HCMenuviewDelegate
- (void)menuProcessByMenuID:(int)menuId
{
    m_operatingType = (ECRMOperatingType)menuId;
    [self setCRMOperatingType:m_operatingType];
    [self.tableView reloadData];
    
    [self menuItemPress:nil];
}


#pragma mark -- HCComMenuCellDelegate
- (void)dataUpdateByMsgID:(int)msgID
{
    /*pause modify---------------------------------------
    switch (msgID)
    {
        case EQueryCustList:
        {
            [self queryCustListDataUpdate];
            break;
        }
        case EQueryCustDetail:
        {
            [self custDetailDataUpdate];
            break;
        }
        default:
        {
            break;
        }
    }
 pause modify-------------------------------------*/
}


- (void)queryCustListDataUpdate
{
    [self.tableView reloadData];
    [self.activityIndicatorView stopAnimating];
    self.activityIndicatorView = nil;
}

- (void)custDetailDataUpdate
{
    [self.activityIndicatorView stopAnimating];
    self.activityIndicatorView = nil;
    
    HCCRMDetailViewController* viewController = [[HCCRMDetailViewController alloc] init];
    HCCRMCustomInfo* info = [[self getDataArray] objectAtIndex:m_menuIndex - 1];
    [viewController showCustomInfoDetail:info];
    
    [self showNextWindow:viewController];
}

@end
